package com.example.lhh.jwt;

import com.alibaba.fastjson2.JSON;
import com.example.lhh.common.LhhResponseJson;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author luoHongHu
 * @Description 过滤器
 * @date 2025年04月01日
 */
public class LhhJwtFilter extends AuthenticatingFilter {

    /**
     * 获取token,没有则创建token
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest =  (HttpServletRequest)servletRequest;
        //获取浏览器上携带的token
        String toke = httpServletRequest.getHeader("Authorization");
        if(StringUtils.isEmpty(toke)){
            return null;
        }
        return new LhhJwtToke(toke);
    }

    /**
     * 进行拦截的具体处理
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest =  (HttpServletRequest)servletRequest;
        //获取浏览器上携带的token
        String toke = httpServletRequest.getHeader("Authorization");
        //是第一次登录
        if(toke == null || toke== "") {//没有token
            return true;
        }
        //有token,则对token进一步进行验证
        Claims claims = LhhJwtUtil.parseJwt(toke);
        //判断token是否过期
        if(claims == null || LhhJwtUtil.isExpire(claims.getExpiration().toString())){
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(new LhhResponseJson<>("401",false,"token无效")));
            return false;
        }
        //执行登录操作
        return executeLogin(servletRequest, servletResponse);
    }

    /**
     * 对跨域提供支持
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
            httpServletResponse.setStatus(200);
            return false;
        }
        return super.preHandle(request, response);
    }
}
